package com.jinlejia.feedback.idea.ui;


import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.feedback.R;
import com.jinlejia.feedback.common.FbApiConfig;
import com.jinlejia.feedback.common.FbDataFilter;
import com.jinlejia.feedback.common.RecycleViewDivider;
import com.jinlejia.feedback.databinding.FbFragmentIdeaAttentionBinding;
import com.jinlejia.feedback.idea.ui.adapter.FbFeedbackAdapter;
import com.jinlejia.feedback.idea.ui.adapter.FBListMapDropDownAdapter;
import com.jinlejia.feedback.idea.ui.bean.FbQuestionListBean;
import com.jinlejia.feedback.question.ui.FbQuestionDetailsActivity;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass
 * 关注.
 */
public class FbIdeaAttentionFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, YfLoadMoreListener {
    private FbFragmentIdeaAttentionBinding binding;
    //下拉列表标题
    private String headers[] = {"处理状态"};
    //下拉列表数据集合
    private List<View> popupViews = new ArrayList<>();
    //下拉列表适配器
    private FBListMapDropDownAdapter menuAdapter;
    //下拉框适配器数据
    private ArrayList<Map<String, Object>> menuroleList = new ArrayList<>();

    //提问列表适配器
    FbFeedbackAdapter fbFeedbackAdapter = new FbFeedbackAdapter(new ArrayList<Map<String, Object>>());

    JSONObject jsonObject = new JSONObject();

    private String state = null;

    private int pageIndex; //查询第几页

    public FbIdeaAttentionFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fb_fragment_idea_attention, container, false);
        binding = DataBindingUtil.bind(view);
        binding.setEvent(this);
        binding.yfListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.yfListRecyclerView.setHasFixedSize(true);
        binding.yfListRecyclerView.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.VERTICAL, 20, Color.parseColor("#F4F4F4")));
        binding.swipeRefreshLayout.setOnRefreshListener(this);
        binding.yfListRecyclerView.enableAutoLoadMore(this);
        binding.yfListRecyclerView.setAdapter(fbFeedbackAdapter);
        fbFeedbackAdapter.changeMode(YfListMode.MODE_LOADING);
        fbFeedbackAdapter.setEventitem(new FbFeedbackAdapter.Eventitem() {
            @Override
            public void itemClick(String problemCode) {
                Intent intent = new Intent(getContext(), FbQuestionDetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("problemCode", problemCode);
                intent.putExtras(bundle);
                getContext().startActivity(intent);
            }
        });
        initView();
        return view;
    }


    /**
     * 下拉列表数据初始化
     */
    private void initView() {
        HashMap<String, Object> hashMap1 = new HashMap<>();
        hashMap1.put("valueName", "未受理");
        HashMap<String, Object> hashMap2 = new HashMap<>();
        hashMap2.put("valueName", "已受理");
        HashMap<String, Object> hashMap3 = new HashMap<>();
        hashMap3.put("valueName", "解决中");
        HashMap<String, Object> hashMap4 = new HashMap<>();
        hashMap4.put("valueName", "已完成");
        HashMap<String, Object> hashMap5 = new HashMap<>();
        hashMap5.put("valueName", "已解决");
        menuroleList.add(hashMap1);
        menuroleList.add(hashMap2);
        menuroleList.add(hashMap3);
        menuroleList.add(hashMap4);
        menuroleList.add(hashMap5);

        final ListView listchuli = new ListView(getContext());
        menuAdapter = new FBListMapDropDownAdapter(getContext(), menuroleList, 1);
        menuAdapter.setData(menuroleList);
        listchuli.setDivider(this.getResources().getDrawable(R.drawable.shape_h_line));
        listchuli.setAdapter(menuAdapter);
        listchuli.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                menuAdapter.setCheckItem(position);
                binding.dropDownMenu.setTabText(position == 0 ? headers[0] : menuroleList.get(position).get("valueName").toString());
                binding.dropDownMenu.closeMenu();
                if (position == 0) {
                    state = null;
                    pageIndex = 1;
                    jsonObject.remove("state");
                    getQuestionList(null, state, 20, pageIndex);
                } else if (position == 1) {
                    state = "0";
                    pageIndex = 1;
                    getQuestionList(null, state, 20, pageIndex);
                } else if (position == 2) {
                    state = "1";
                    pageIndex = 1;
                    getQuestionList(null, state, 20, pageIndex);
                } else if (position == 3) {
                    state = "2";
                    pageIndex = 1;
                    getQuestionList(null, state, 20, pageIndex);
                } else if (position == 4) {
                    state = "3";
                    pageIndex = 1;
                    getQuestionList(null, state, 20, pageIndex);
                } else if (position == 5) {
                    state = "4";
                    pageIndex = 1;
                    getQuestionList(null, state, 20, pageIndex);
                }

            }
        });
        popupViews.add(listchuli);
        TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);
        binding.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);
    }


    /**
     * 网络请求问题列表数据
     */
    public void getQuestionList(String keyWord, String state, int pageSize, final int pageIndex) {
        if (!TextUtils.isEmpty(state)) {
            jsonObject.put("state", Integer.parseInt(state));
        }

        if (!TextUtils.isEmpty(keyWord)) {
            jsonObject.put("keyWord", keyWord);
        }
        jsonObject.put("pageSize", pageSize);
        jsonObject.put("pageIndex", pageIndex);
        jsonObject.put("type", 1);

        OkHttpUtils.postString()
                .url(FbApiConfig.GetQuestionList)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        binding.swipeRefreshLayout.setRefreshing(false);
                        CustomToast.showToast(getContext(), "网络错误" + e.toString(), 1500);
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        ArrayList<Map<String, Object>> data = new ArrayList<>();
                        int code = FbDataFilter.code(response);
                        if (code==700){
                            fbFeedbackAdapter.changeMode(YfListMode.MODE_ERROR);
                            return;
                        }
                        if (code == 200 && !showEmptyMessage(response)) {
                            JSONArray dataList = (JSONArray) response.get("data");
                            List<FbQuestionListBean> questionListBeans = JSON.parseArray(dataList.toString(), FbQuestionListBean.class);
                            for (FbQuestionListBean questionListBean : questionListBeans) {
                                HashMap<String, Object> map = new HashMap<>();
                                map.put("problemCode", questionListBean.getProblemCode());
                                map.put("problemTitle", questionListBean.getProblemTitle());
                                map.put("askTime", questionListBean.getAskTime());
                                map.put("isGeneral", questionListBean.getIsGeneral());
                                map.put("state", questionListBean.getState());
                                data.add(map);
                            }
                            if (pageIndex == 1) {
                                fbFeedbackAdapter.setData(data);
                            } else {
                                fbFeedbackAdapter.addData(data);
                            }
                        } else {
                            binding.yfListRecyclerView.enableAutoLoadMore(null);
                            if (pageIndex == 1) {
                                fbFeedbackAdapter.setData(data);
                            } else {
                                fbFeedbackAdapter.addData(data);
                            }
                        }
                        fbFeedbackAdapter.notifyDataSetChanged();
                        binding.swipeRefreshLayout.setRefreshing(false);
                    }
                });
    }

    private boolean showEmptyMessage(Map<String, Object> response) {
        if ("501".equals(String.valueOf(response.get("code")))) {
            if (response.get("message") != null)
                return true;
        }
        return false;
    }

/**
 * 处理搜索回调刷新列表展示搜索结果
 * */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 104) {
            String name = data.getStringExtra("data");
            pageIndex = 1;
            getQuestionList(name, state, 20, pageIndex);
        } else if (resultCode == RESULT_CANCELED && requestCode == 104) {
            jsonObject.remove("keyWord");
            pageIndex = 1;
            getQuestionList(null, state, 20, pageIndex);
        }
    }

/**
 * 上拉刷新
 * */
    @Override
    public void onRefresh() {
        pageIndex = 1;
        binding.yfListRecyclerView.enableAutoLoadMore(this);
        binding.swipeRefreshLayout.setRefreshing(true);
        getQuestionList(null, state, 20, pageIndex);
    }
/**
 * 下拉加载更多
 * */
    @Override
    public void loadMore() {
        pageIndex = pageIndex + 1;
        getQuestionList(null, state, 20, pageIndex);
    }


    @Override
    public void onStart() {
        super.onStart();
        pageIndex = 1;
        getQuestionList(null, state, 20, pageIndex);
    }
}
